//
//  WZDelayDetailViewController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 16/8/31.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZDelayDetailViewController.h"
#import "DateHelper.h"
#import "NSDate+CalculateDay.h"
#import "KMDatePicker.h"
#import "WZDetailTask.h"
#import "JKAlertDialog.h"

#define TaskManager_delayTask_Success            @"保存成功"
#define TaskManager_delayTask_Remind             @"延期原因不能为空"
#define TaskManager_delayTask_BackItem_Title     @"提示"
#define TaskManager_delayTask_BackItem_message   @"确定放弃延期申请?"
#define TaskManager_delayTask_BackItem_CancelBtn @"取消"
#define TaskManager_delayTask_BackItem_DoneBtn   @"确定"
#define TaskManager_delayTask_Reason             @"延期原因说明"
#define TaskManager_delayTask_DelayDate          @"延期日期不能为空"

@interface WZDelayDetailViewController ()<UITextFieldDelegate, UITextViewDelegate, KMDatePickerDelegate, UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UITextView  *delayReasionTextView;
@property (weak, nonatomic) IBOutlet UITextField *delayDateTF;
@property (nonatomic, weak) IBOutlet UILabel     *characterCount;
@property (nonatomic, strong) NSDate *delayDate;
@end

@implementation WZDelayDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupDelayDetailView];
    
    [self setupDatePicker];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [_delayDateTF addTarget:self action:@selector(textFieldChanged) forControlEvents:UIControlEventValueChanged];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [_delayDateTF becomeFirstResponder];
}

- (void)setupDelayDetailView {
    
    self.view.backgroundColor = RGBCOLORWITH16COLOR(0xf5f5f5);
    self.navigationItem.title = @"申请延期";
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(backBtnDidClick) titleFont:Font18 titleColor:WhiteColor];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"taskManager_refuse_nav_right" title:nil target:self sel:@selector(applyDelayBtnDidClick) titleFont:Font12 titleColor:WhiteColor];
//    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *dateStr = [formatter stringFromDate:date];
    NSDate *plainDate = [NSDate dateFromString:_detailTask.planExecEndDate format:@"yyyy-MM-dd HH:mm"];
    NSTimeInterval second = 1 * 60 * 60;
    NSDate *delayDate = [NSDate dateWithTimeInterval:second sinceDate:plainDate];
    self.delayDate = delayDate;
    
    _delayDateTF.text = [NSDate datestrFromDate:delayDate withDateFormat:@"yyyy-MM-dd HH:mm"];
    
    WZLog(@"NSDate = %@, dateStr = %@", date, dateStr);
}


- (void)setupDatePicker {
    
    CGRect rect = [[UIScreen mainScreen] bounds];
    rect = CGRectMake(0.0, 0.0, rect.size.width, 216.0);
    KMDatePicker *datePick = [[KMDatePicker alloc] initWithFrame:rect delegate:self datePickerStyle:0];
    self.delayDateTF.inputView = datePick;
}

#pragma mark - 延期确认

- (void)applyDelayBtnDidClick {
    
    // 比较日期
//    NSDate *selDate = [NSDate dateFromString:_delayDateTF.text format:@"yyyy-MM-dd HH:mm"];
//    NSComparisonResult result = [selDate compare:_delayDate];
    
    if ([_delayReasionTextView.text isEqualToString:TaskManager_delayTask_Reason]) {
        
        [MBProgressHUD showError:TaskManager_delayTask_Remind];
        return;
    }
    
    if (!_delayDateTF.text.length) {
        [MBProgressHUD showError:TaskManager_delayTask_DelayDate];
        return;
    }
    
    NSString *delayTimeStamp = [NSDate cTimestampStringFromString:self.delayDateTF.text format:@"yyyy-MM-dd HH:mm"];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"name"] = self.oaUserName;
    params[@"pwd"] = self.oaPwd;
    params[@"taskId"] = self.taskId;
    params[@"delayDate"] = delayTimeStamp;
    params[@"remark"] = self.delayReasionTextView.text;
    
    [NetWorkShare applyForDelayWithParams:params SuccessHandle:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            
            if ([responseObject objectForKey:@"success"]) {
                WZLog(@"result = %@", responseObject);
                
                [MBProgressHUD showSuccess:TaskManager_delayTask_Success toView:self.view];
                
                if(_block) {
                    _block(_delayDateTF.text);
                }
                
                [self.navigationController popViewControllerAnimated:YES];
                
            } else {
                
                [MBProgressHUD showError:[responseObject objectForKey:@"message"]];
            }
        } else {
            
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:UNKNOWNERROR];
        }
    } FailureHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:NETWORKNERROR];
        WZLog(@"error = %@", error);
    }];
}

#pragma mark - 隐藏键盘

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.delayReasionTextView resignFirstResponder];
    [self.view resignFirstResponder];
    [super touchesBegan:touches withEvent:event];
}

#pragma mark - textView Delegate

- (void)textViewDidChange:(UITextView *)textView {
    
    WZLog(@"textViewDidChange");
    if (textView.text.length <= 500) {
        self.characterCount.text = [NSString stringWithFormat:@"%lu/500", 500 - textView.text.length];
        
    } else {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            textView.text = [textView.text substringToIndex:500];
            _characterCount.text = @"0/500";
            [textView endEditing:YES];
        });
    }
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if(range.location > 500){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"输入的自字符数不能超过500"
                                                       delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
        
    }else{
        
        return YES;
    }
}

- (NSUInteger) unicodeLengthOfString: (NSString *) text {
    NSUInteger asciiLength = 0;
    for (NSUInteger i = 0; i < text.length; i++) {
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    NSUInteger unicodeLength = asciiLength / 2;
    if(asciiLength % 2) {
        unicodeLength++;
    }
    return unicodeLength;
}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
//    WZLog(@"textViewShouldBeginEditing");
    return YES;
}


- (void)textViewDidBeginEditing:(UITextView *)textView {
    
    WZLog(@"DidBeginEditing");
    
    if ([textView.text isEqualToString:TaskManager_delayTask_Reason]) {
        
        textView.text = @"";
        [textView setTextColor:[UIColor blackColor]];
    }
}


- (void)textViewDidEndEditing:(UITextView *)textView {
    
    WZLog(@"textViewDidEndEditing");
    
    if (textView.text.length < 1) {
        
        textView.text = TaskManager_delayTask_Reason;
        [textView setTextColor:[UIColor grayColor]];
        textView.backgroundColor = WZRGBColor(247, 246, 250);
    }
}


- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
    //    [textView setBackgroundColor:[UIColor redColor]];
//    WZLog(@"textViewShouldEndEditing");
    return YES;
}


#pragma mark - TextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [_delayDateTF resignFirstResponder];
    return YES;
}


#pragma mark - datePic Delegate 

- (void)datePicker:(KMDatePicker *)datePicker didSelectDate:(KMDatePickerDateModel *)datePickerDate {
    
    switch (datePicker.datePickerStyle) {
        case KMDatePickerStyleYearMonthDayHourMinute: {
            
            self.delayDateTF.text = [NSString stringWithFormat:@"%@-%@-%@ %@:%@", datePickerDate.year, datePickerDate.month, datePickerDate.day, datePickerDate.hour, datePickerDate.minute];
            break;
        }
        case KMDatePickerStyleYearMonthDay: {
            
            
            break;
        }
        case KMDatePickerStyleMonthDayHourMinute: {
            
            
            break;
        }
        case KMDatePickerStyleHourMinute: {
            
            
            break;
        }
    }
}


- (void)setupAlertView {
    
    if ([[UIDevice currentDevice].systemVersion doubleValue] < 8.0) {
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:TaskManager_delayTask_BackItem_Title message:TaskManager_delayTask_BackItem_message delegate:self cancelButtonTitle:TaskManager_delayTask_BackItem_CancelBtn otherButtonTitles:TaskManager_delayTask_BackItem_DoneBtn, nil];
        
        [alertView show];
        
    } else if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) {
        
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:TaskManager_delayTask_BackItem_Title message:TaskManager_delayTask_BackItem_message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:TaskManager_delayTask_BackItem_CancelBtn style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            // cancel 回调
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:TaskManager_delayTask_BackItem_DoneBtn style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        [alertVc addAction:action1];
        [alertVc addAction:action2];
        
        [self presentViewController:alertVc animated:YES completion:nil];
    }
}

#pragma mark - alertView Delegatet
- (void)alertViewCancel:(UIAlertView *)alertView {
    
    WZLog(@"cancel button click");
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    WZLog(@"done button click");
    
}


// 按钮点击的代理方法
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    WZLog(@"alertView dismiiss");
    
    switch (buttonIndex) {
        case 0:
            
            // cancel 按钮什么也不做
            break;
            
        case 1:
            
            
            [self.navigationController popViewControllerAnimated:YES];
            break;
            
        default:
            break;
    }
}


#pragma mark - 返回按钮点击方法
- (void)backBtnDidClick {
    
    [_delayReasionTextView endEditing:YES];
    
    if ([_delayReasionTextView.text isEqualToString:TaskManager_delayTask_Reason]) {
        
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    
//    [self setupAlertView];
    
    __block WZDelayDetailViewController *block = self;
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:TaskManager_delayTask_BackItem_message];
    [alert addButton:Button_OK withTitle:TaskManager_delayTask_BackItem_DoneBtn handler:^(JKAlertDialogItem *item) {
        
        [block.navigationController popViewControllerAnimated:YES];
    }];
    
    [alert addButton:Button_CANCEL withTitle:TaskManager_delayTask_BackItem_CancelBtn handler:^(JKAlertDialogItem *item) {
        
        
    }];
    
    [alert show];
}


- (void)textFieldChanged {
    
    self.navigationItem.rightBarButtonItem.enabled = self.delayDateTF.text.length;
}


@end
